package com.cunyu.action;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.InitBinder;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.serializer.SerializerFeature;

import cn.tom.kit.cache.TimedCache;
import com.cunyu.listener.RequestContext;

/**
 * 
 * @author tomsun
 *
 */
public class OpenController {
	
	@Resource
	protected TimedCache<String, Object> timedCache;
	
	public boolean before(HttpServletRequest req, HttpServletResponse res){
		setCros(req, res);
		return true;
	}

	public void setCros(HttpServletRequest req,HttpServletResponse res){
		String allowMethod = req.getHeader("Access-Control-Request-Method");
		if(allowMethod == null) return;
        String allowHeaders = req.getHeader("Access-Control-Request-Headers");
        res.setHeader("Access-Control-Max-Age", "86400");  
        res.setHeader("Access-Control-Allow-Credentials", "true");
        res.setHeader("Access-Control-Allow-Origin", "*");  //http://tg.baisha.work
        res.setHeader("Access-Control-Allow-Methods", allowMethod); //GET, POST, PUT, DELETE, OPTIONS
        res.setHeader("Access-Control-Allow-Headers", allowHeaders); //"X-Requested-With, Content-Type, Accept, withCredentials"
	}

	@InitBinder
	protected void initBinder(HttpServletRequest request,
			ServletRequestDataBinder binder) throws Exception {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		CustomDateEditor dateEditor = new CustomDateEditor(format, true);
		binder.registerCustomEditor(Date.class, dateEditor);
	}

	public  void printHTML(HttpServletResponse res, Object html) {
		render(res, html, "text/html;charset=UTF-8");
	};

	public void printJSON(HttpServletResponse res, Object obj) {
		if (obj instanceof String) {
			render(res, obj, "application/json;charset=UTF-8");
			return;
		}
		try {
			render(res, JSON.toJSONString(obj,SerializerFeature.DisableCircularReferenceDetect, SerializerFeature.WriteNullStringAsEmpty, SerializerFeature.WriteMapNullValue,SerializerFeature.WriteDateUseDateFormat),
					"application/json;charset=UTF-8");
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}
	
	
	public void printOK(HttpServletResponse res,String msg, Object... obj){
		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("state", "000");
		map.put("msg", msg);
		if(obj.length>0){
			map.put("data", obj[0]);
		}
		printJSON(res, map);
	}
	
	public void printError(HttpServletResponse res, String msg, Object... obj){
		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("state", "001");
		map.put("msg", msg);
		if(obj.length>0){
			map.put("data", obj[0]);
		}
		printJSON(res, map);
	}
	

	private void render(HttpServletResponse response, Object text,
			String contentType) {
		response.setHeader("Pragma", "No-cache");
		response.setHeader("Cache-Control", "no-cache, must-revalidate");
		response.setDateHeader("Expires", 0L);
		response.setContentType(contentType);
		try {
			response.getWriter().print(text);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public void setToken(){
		String token = ""+System.currentTimeMillis();
		RequestContext.get().setCookie("token", token, 120);
		RequestContext.get().getSession().setAttribute("token", token);
	}

	public boolean checkToken(String token){
		if(token.equals(RequestContext.get().getSession().getAttribute("token"))){
			RequestContext.get().getSession().removeAttribute("token");
			return true;
		}
		return false;
	}
//	public void setVelidateToken(String tel){
//	String token = ""+System.currentTimeMillis();
//	RedisUtil.getInstance().set(tel, token);
//	RequestContext.get().setCookie("velidateToken", token, 120);
//}
//
//public boolean checkVelidateToken(String tel, String token){
//	if(token.equals(RedisUtil.getInstance().get(tel))){
//		RedisUtil.getInstance().del(tel);
//		return true;
//	}
//	return false;
//}
}
